package com.lp.easydraw.adapter;

import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.lp.easydraw.R;
import com.lp.easydraw.data.DrawColorData;

import java.util.ArrayList;
import java.util.List;

public class ColorGridAdapter extends RecyclerView.Adapter<ColorGridAdapter.ColorViewHolder> {
    private static final String TAG = "ColorGridAdapter";
    private List<DrawColorData> colorList;
    private ImageButton chooseButton;

    public interface IColorChoose {
        void choose(DrawColorData color);
    }

    private IColorChoose iColorChoose;

    private void initDataList() {
        colorList = new ArrayList<>();
        colorList.add(new DrawColorData(R.drawable.black, R.color.black));
        colorList.add(new DrawColorData(R.drawable.white, R.color.white));
        colorList.add(new DrawColorData(R.drawable.red_circle, R.color.red));
        colorList.add(new DrawColorData(R.drawable.blue, R.color.blue));
        colorList.add(new DrawColorData(R.drawable.gray, R.color.gray));
        colorList.add(new DrawColorData(R.drawable.cyan, R.color.cyan));
    }

    public ColorGridAdapter(IColorChoose iColorChoose) {
        initDataList();
        this.iColorChoose = iColorChoose;
    }

    @NonNull
    @Override
    public ColorGridAdapter.ColorViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.color_item, parent, false);
        ColorViewHolder holder = new ColorViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ColorGridAdapter.ColorViewHolder holder, int position) {
        Log.i(TAG, "onBindViewHolder: ");
        holder.imageButton.setImageResource(colorList.get(position).getColorSrcId());
        holder.imageButton.setOnClickListener(view -> {
            if (chooseButton != null)
                chooseButton.setSelected(false);
            iColorChoose.choose(colorList.get(position));
            chooseButton = holder.imageButton;
            chooseButton.setSelected(true);
        });
    }

    @Override
    public int getItemCount() {
        return colorList.size();
    }

    public class ColorViewHolder extends RecyclerView.ViewHolder {
        private ImageButton imageButton;

        public ColorViewHolder(@NonNull View itemView) {
            super(itemView);
            imageButton = itemView.findViewById(R.id.ib_color);

        }

    }
}
